package com.leetcode;

/**
 * 202. 快乐数
 * 快慢指针法  检测死循环来退出
 *
 * @author fy
 * @date 2022/4/6 15:02
 */
public class Solution202_1 {

    public boolean isHappy(int n) {
        int slower = n;
        int faster = getNext(n);
        while (n != 1 && slower != faster) {
            slower = getNext(slower);
            faster = getNext(getNext(faster));
        }
        return faster == 1;
    }

    private int getNext(int n) {
        int sum = 0;
        while (n > 0) {
            int m = n % 10;
            sum += m * m;
            n = n / 10;
        }
        return sum;
    }
}
